<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Requests\AuthLoginRequest;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{

    public function store(AuthLoginRequest $request)
    {
        $username = $request->username;

        filter_var($username, FILTER_VALIDATE_EMAIL) ?
            $credentials['email'] = $username :
            $credentials['phone'] = $username;

        $credentials['password'] = $request->password;

        if (!$token = auth('api')->attempt($credentials)) {
            return $this->response->errorUnauthorized('用户名或密码错误');
        }

        filter_var($username, FILTER_VALIDATE_EMAIL) ?
        User::where('email',$request->username)->update(['login_ip'=>$request->getClientIp()]):
        User::where('phone',$request->username)->update(['login_ip'=>$request->getClientIp()]);

        return $this->respondWithToken($token);
    }

    protected function respondWithToken($token)
    {
        $expiresIn = auth('api')->factory()->getTTL() * 600;
        //'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
        return $this->response->array(
            [
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => $expiresIn,
            ]
        )->setStatusCode(201);
    }

    public function update()
    {
        $token = \Auth::guard('api')->refresh();
        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        \Auth::guard('api')->logout();
        return $this->response->noContent();
    }
}
